package com.zzq.controller;

import com.alibaba.fastjson.JSON;
import com.zzq.pojo.Result;
import com.zzq.service.MinioStorageService;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/minio")
@Slf4j
public class MinioController {

        @Value("${minio.endpoint}")
        private String endpoint;

        @Value("${minio.bucket}")
        private String bucketName;

        @Autowired
        private MinioStorageService minioStorageService;

    @Autowired
    private MinioClient minioClient;

        @PostMapping("/uploadFile")
        public Result uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fileName") String fileName) throws IOException {

            try {
                // 生成唯一文件名，避免冲突
                String newFileName = UUID.randomUUID().toString().replace("-", "") + "_" + fileName;

                // 上传文件到MinIO
                String objectName = minioStorageService.uploadFile(file.getInputStream(), newFileName);
                log.info("文件上传成功: {}", objectName);

                // 生成预签名URL
                GetPresignedObjectUrlArgs presignedArgs = GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(7, TimeUnit.DAYS) // 设置URL有效期
                        .build();

                String presignedUrl = minioClient.getPresignedObjectUrl(presignedArgs);

                // 返回给前端的信息
                Map<String, Object> data = new HashMap<>();
                data.put("fileName", fileName); // 原始文件名
                data.put("fileUrl", presignedUrl); // 预签名URL，带访问权限
                data.put("fileSize", file.getSize());

                return Result.success(data);
            } catch (Exception e) {
                log.error("文件上传失败", e);
                return Result.error(500,"文件上传失败: " + e.getMessage());
            }
        }

}

